﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Browser;

namespace SilveR
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            RegisterOnBeforeUnload();
        }

        // After the Frame navigates, ensure the HyperlinkButton representing the current page is selected
        private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            foreach (UIElement child in LinksStackPanel.Children)
            {
                HyperlinkButton hb = child as HyperlinkButton;
                if (hb != null && hb.NavigateUri != null)
                {
                    if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
                    {
                        VisualStateManager.GoToState(hb, "ActiveLink", true);
                    }
                    else
                    {
                        VisualStateManager.GoToState(hb, "InactiveLink", true);
                    }
                }
            }
        }

        // If an error occurs during navigation, show an error window
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ChildWindow errorWin = new ErrorWindow(e.Uri);
            errorWin.Show();
        }       


        public void RegisterOnBeforeUnload()
        {
            //Register Silverlight object for availability in Javascript.
            const string scriptableObjectName = "silverlightControlHost";
            HtmlPage.RegisterScriptableObject(scriptableObjectName, this);

            //Start listening to Javascript event
            string pluginName = HtmlPage.Plugin.Id;
            HtmlPage.Window.Eval(string.Format(
                @"window.onbeforeunload = function () {{
                var slApp = document.getElementById('{0}');
                var result = slApp.Content.{1}.OnBeforeUnload();
                if(result.length > 0)
                    return result;
            }}", pluginName, scriptableObjectName)
    );
        }

        [ScriptableMember]
        public string OnBeforeUnload()
        {
            App app = (App)Application.Current;

            DataPage dataPage = app.DataPage;
            AnalysesPage analysesPage = app.AnalysesPage;

            //if there are data or analyses pages then show a message before exiting
            if ((dataPage != null && app.DataPage.tabControlData.Items.Count > 0) || (analysesPage!= null && app.AnalysesPage.tabControlAnalyses.Items.Count > 0))
            {
                return "If you do all data and analyses in SilveR will be closed.";
            }
            else
            {
                return string.Empty;
            }
        }
    }
}